package com.cmc.cloud.cmclink.doc.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Description: 配置spring事件的异步线程池
 * @author: wuzhongwang
 * @date: 2021-09-08 10:21
 */
@Slf4j
@Configuration
public class ThreadPoolUtils {

    /**
     * 只支持【异步事件处理】的线程池 核心线程数固定
     *
     * @return 线程池
     */
    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        // 核心线程数
        taskExecutor.setCorePoolSize(4);
        // 最大线程数
        taskExecutor.setMaxPoolSize(128);
        // 队列大小
        taskExecutor.setQueueCapacity(2000);
        // 线程名的前缀
        taskExecutor.setThreadNamePrefix("async-asyncEvent-thread-");
        // 线程池对拒绝任务（无线程可用）的处理策略，目前只支持AbortPolicy、CallerRunsPolicy；默认为后者
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

}
